package cn.actoncode.boot.module.ai.api.user;

import cn.actoncode.boot.framework.security.core.LoginUser;
import cn.actoncode.boot.module.ai.controller.app.user.vo.UserUpdateReqVO;
import cn.actoncode.boot.module.ai.convert.user.MemberUserConvert;
import cn.actoncode.boot.module.ai.dal.dataobject.user.MemberUserDO;
import cn.actoncode.boot.module.ai.dal.redis.auth.LoginUserRedisDAO;
import cn.actoncode.boot.module.ai.service.user.MemberUserService;
import cn.actoncode.boot.module.member.api.user.dto.LoginUserDTO;
import cn.actoncode.boot.module.member.api.user.dto.MemberUserRespDTO;
import cn.actoncode.boot.module.member.api.user.dto.UserInfoDTO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.actoncode.boot.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.actoncode.boot.module.ai.enums.DictionaryConstants.*;
import static cn.actoncode.boot.module.ai.enums.ErrorCodeConstants.USER_FREEZE;
import static cn.actoncode.boot.module.ai.enums.ErrorCodeConstants.USER_LOCKED;

/**
 * 成员用户的 API 实现类
 *
 * @author bin
 */
@Service
@Validated
public class MemberUserApiImpl implements MemberUserApi {

    @Resource
    private MemberUserService memberUserService;

    @Resource
    private LoginUserRedisDAO loginUserRedisDAO;

    @Override
    public MemberUserRespDTO getUser(Long id) {
        MemberUserDO user = memberUserService.getUserByUserId(id);
        return MemberUserConvert.INSTANCE.convert03(user);
    }

    @Override
    public LoginUserDTO getLoginUser(Long userId) {

        // 先去redis取用户信息
        // 如果有则证明用户信息无变化，直接获取。没有则去数据库取最新用户信息
        LoginUser loginUser = loginUserRedisDAO.get(userId);
        if (null != loginUser) {
            LoginUserDTO loginUserDTO = MemberUserConvert.INSTANCE.convert(loginUser);
            loginUserDTO.setState(USER_STATE_NORMAL);
            return loginUserDTO;
        }
        // 数据库获取用户
        LoginUserDTO loginUserDTO = MemberUserConvert.INSTANCE.convert(memberUserService.getUserByUserId(userId));
        // 校验用户
        validate(loginUserDTO);
        // 缓存登录用户
        loginUser = MemberUserConvert.INSTANCE.convert(loginUserDTO);
        loginUserRedisDAO.set(loginUser);
        return loginUserDTO;
    }

    @Override
    public UserInfoDTO getUserInfo(Long userId) {
        return MemberUserConvert.INSTANCE.convert02(memberUserService.getUserByUserId(userId));
    }

    private void validate(LoginUserDTO MemberUserDO) {

        if (USER_STATE_FREEZE == MemberUserDO.getState()) {
            throw exception(USER_FREEZE);
        }

        if (USER_STATE_LOCKED == MemberUserDO.getState()) {
            throw exception(USER_LOCKED);
        }
    }

}
